package org.glut.cloud.repairManage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.glut.cloud.repairManage.entity.FailureRepair1;
import org.glut.cloud.repairManage.service.IFailureRepair1Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * 故障保修表 前端控制器
 *
 * @author sanmingzhi
 * @since 2024-08-13 19:10
 */
@RestController
@RequestMapping("/failure-repair1")
public class FailureRepair1Controller {

    @Autowired
    private IFailureRepair1Service failureRepair1Service;
    @Autowired
    private SimpMessagingTemplate messagingTemplate;  // 注入 SimpMessagingTemplate

    /**
     * 根据 ID 获取故障报修信息
     *
     * @param id 故障报修的 ID
     * @return 对应的故障报修信息
     */
    @GetMapping("/{id}")
    public ResponseEntity<FailureRepair1> getFailureRepairById(@PathVariable Integer id) {
        FailureRepair1 repair = failureRepair1Service.getById(id);
        if (repair == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(repair);
    }

    /**
     * 获取所有故障报修记录
     *
     * @return 所有故障报修记录的列表
     */
    @GetMapping("/list")
    public ResponseEntity<?> getFailureRepairs(
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "5") int size,
            @RequestParam(value = "query", required = false) String query
    ) {
        QueryWrapper<FailureRepair1> queryWrapper = new QueryWrapper<>();
        if (query != null && !query.trim().isEmpty()) {
            queryWrapper.lambda().like(FailureRepair1::getFullName, query)
                    .or().like(FailureRepair1::getFailureRepairId, query);
        }
        Page<FailureRepair1> repairPage = new Page<>(page, size);
        Page<FailureRepair1> resultPage = failureRepair1Service.page(repairPage, queryWrapper);

        return ResponseEntity.ok(resultPage);
    }

    /**
     * 审批故障报修
     *
     * @param id 故障报修的 ID
     * @return 审批结果
     */
    @PutMapping("/approve/{id}")
    public ResponseEntity<Boolean> approveFailureRepair(@PathVariable Integer id) {
        FailureRepair1 repair = failureRepair1Service.getById(id);
        if (repair == null) {
            return ResponseEntity.notFound().build();
        }
        repair.setRepairStatus("已审批");
        boolean updated = failureRepair1Service.updateById(repair);

        // 通过 WebSocket 发送通知
        if (updated) {
            messagingTemplate.convertAndSend("/topic/repairs",id +  "号报修单被审批，请及时更新网页");
        }

        return ResponseEntity.ok(updated);
    }

    /**
     * 获取所有未处理的故障报修记录
     *
     * @return 未处理的故障报修记录列表
     */
    @GetMapping("/unfinished")
    public ResponseEntity<List<FailureRepair1>> getUnfinishedFailureRepairs() {
        QueryWrapper<FailureRepair1> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("repair_status", "待处理");
        List<FailureRepair1> repairs = failureRepair1Service.list(queryWrapper);
        return ResponseEntity.ok(repairs);
    }



    /**
     * 获取所有已审批的故障报修记录
     *
     * @return 已审批的故障报修记录列表
     */
    @GetMapping("/approved")
    public ResponseEntity<List<FailureRepair1>> getApprovedFailureRepairs() {
        QueryWrapper<FailureRepair1> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("repair_status", "已审批");
        List<FailureRepair1> repairs = failureRepair1Service.list(queryWrapper);
        return ResponseEntity.ok(repairs);
    }


    /**
     * 导出所有已审批的故障报修记录为 Excel 文件
     *
     * @param response HTTP 响应
     * @return 包含 Excel 文件的响应实体
     */
    @GetMapping("/export")
    public ResponseEntity<byte[]> exportApprovedRepairs() {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("Approved Repairs");
            Row header = sheet.createRow(0);
            header.createCell(0).setCellValue("报修ID");
            header.createCell(1).setCellValue("用户姓名");
            header.createCell(2).setCellValue("类型");
            header.createCell(3).setCellValue("标题");
            header.createCell(4).setCellValue("报修时间");
            header.createCell(5).setCellValue("状态");

            List<FailureRepair1> approvedRepairs = failureRepair1Service.list(
                    new QueryWrapper<FailureRepair1>().eq("repair_status", "已审批")
            );

            int rowNum = 1;
            for (FailureRepair1 repair : approvedRepairs) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(repair.getFailureRepairId());
                row.createCell(1).setCellValue(repair.getFullName());
                row.createCell(2).setCellValue(repair.getType());
                row.createCell(3).setCellValue(repair.getTitle());
                row.createCell(4).setCellValue(repair.getRepairTime().toString());
                row.createCell(5).setCellValue(repair.getRepairStatus());
            }

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            workbook.write(out);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attachment; filename=approved_repairs.xlsx");
            return new ResponseEntity<>(out.toByteArray(), headers, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
